﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Windows;
using System.Windows.Controls;
using Logistics.DataManage.DB;

namespace Logistics.Win
{
    /// <summary>
    /// Interaction logic for PanelServerSetting.xaml
    /// </summary>
    public partial class PanelServerSetting : UserControl
    {
        protected ServerSetting SettingModel { get; set; }

        public PanelServerSetting()
        {
            this.SettingModel = new ServerSetting();
            InitializeComponent();
        }
        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            IniteSetting();
        }

        /// <summary>
        /// 初始化
        /// </summary>
        private void IniteSetting()
        {
            String oraString = ConnectStringMgr.ConnectString_Oracle;
            IDictionary<String, String> dict = ParseConnectionString(oraString);
            if (dict.ContainsKey("host"))
                SettingModel.ServerIP=dict["host"];
            if (dict.ContainsKey("port"))
                SettingModel.ServerPort = Convert.ToInt32(dict["port"]);
            if (dict.ContainsKey("serviceName"))
                SettingModel.ServiceName = dict["serviceName"];
            if (dict.ContainsKey("userName"))
                SettingModel.UserName = dict["userName"];
            if (dict.ContainsKey("password"))
                this.passwordBox.Password = dict["password"];

            this.DataContext = SettingModel;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnSave_Click(object sender, RoutedEventArgs e)
        {
            String serverIP = this.SettingModel.ServerIP;
            if (String.IsNullOrWhiteSpace(serverIP))
            {
                MessageBox.Show("服务器IP地址不能为空");
                return;
            }
            int port = this.SettingModel.ServerPort;

            String serviceName = this.SettingModel.ServiceName;
            if (String.IsNullOrWhiteSpace(serviceName))
            {
                MessageBox.Show("服务名不能为空");
                return;
            }
            String userName = this.SettingModel.UserName;
            String password = this.passwordBox.Password;
            if (String.IsNullOrWhiteSpace(userName))
            {
                MessageBox.Show("用户名不能为空");
                return;
            }
            if (String.IsNullOrWhiteSpace(password))
            {
                MessageBox.Show("密码不能为空");
                return;
            }
            //更新当前用户的信息
            String connectStringTemplate = "Data Source= (DESCRIPTION =(ADDRESS = (PROTOCOL = TCP)(HOST ={0})(PORT = {1}))(CONNECT_DATA =(SERVICE_NAME = {2})));User ID={3};Password={4};";
            String connectString = String.Format(connectStringTemplate, serverIP, port, serviceName, userName, password);
            SaveOraConnectionString(connectString);

            //刷新连接串信息
            ConnectStringMgr.ConnectString_Oracle = connectString;

            Xceed.Wpf.Toolkit.MessageBox.Show("保存成功");
        }

        private void SaveOraConnectionString(String connectionString)
        {
            String key = "ORACLE";
            //新建一个连接字符串实例  
            ConnectionStringSettings mySettings = new ConnectionStringSettings(key, connectionString, null);

            System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            config.ConnectionStrings.ConnectionStrings.Remove(key);
            config.ConnectionStrings.ConnectionStrings.Add(mySettings);
            // 保存对配置文件所作的更改  
            config.Save(ConfigurationSaveMode.Modified);
            // 强制重新载入配置文件的ConnectionStrings配置节  
            ConfigurationManager.RefreshSection("ConnectionStrings"); 
        }

        private IDictionary<String, String> ParseConnectionString(String connectionString)
        {
            IDictionary<String, String> dict = new Dictionary<String, String>();
            String[] parts = connectionString.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
            if (parts.Length == 3)
            {
                String cstring=parts[0];

                int index = cstring.IndexOf("HOST");
                int last = cstring.IndexOf(')',index);
                String hostString = cstring.Substring(index, last - index);
                String[] segs = hostString.Split(new char[] { '=' }, StringSplitOptions.RemoveEmptyEntries);
                dict.Add("host", segs[1]);

                index = cstring.IndexOf("PORT");
                last = cstring.IndexOf(')', index);
                String portString = cstring.Substring(index, last - index);
                segs = portString.Split(new char[] { '=' }, StringSplitOptions.RemoveEmptyEntries);
                dict.Add("port", segs[1].Trim());

                index = cstring.IndexOf("SERVICE_NAME");
                last = cstring.IndexOf(')', index);
                String svcString = cstring.Substring(index, last - index);
                segs = svcString.Split(new char[] { '=' }, StringSplitOptions.RemoveEmptyEntries);
                dict.Add("serviceName", segs[1].Trim());

                segs = parts[1].Split(new char[] { '=' }, StringSplitOptions.RemoveEmptyEntries);
                dict.Add("userName", segs[1].Trim());

                segs = parts[2].Split(new char[] { '=' }, StringSplitOptions.RemoveEmptyEntries);
                dict.Add("password", segs[1].Trim());
            }
            return dict;
        }
        
        /// <summary>
        /// 
        /// </summary>
        public class ServerSetting : INotifyPropertyChanged
        {
            public event PropertyChangedEventHandler PropertyChanged;
            public void RaisePropertyChanged(string propertyName)
            {
                if (PropertyChanged != null)
                {
                    PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
                }
            }

            private String _ServerIP;
            public String ServerIP{
                get { return _ServerIP; }
                set
                {
                    if (_ServerIP != value)
                    {
                        _ServerIP = value;
                        RaisePropertyChanged("ServerIP");
                    }
                }
            }

            private int _ServerPort;
            public int ServerPort
            {
                get { return _ServerPort; }
                set
                {
                    if (_ServerPort != value)
                    {
                        _ServerPort = value;
                        RaisePropertyChanged("ServerPort");
                    }
                }
            }
            
            private String _ServiceName;
            public String ServiceName
            {
                get { return _ServiceName; }
                set
                {
                    if (_ServiceName != value)
                    {
                        _ServiceName = value;
                        RaisePropertyChanged("ServiceName");
                    }
                }
            }

            private String _UserName;
            public String UserName
            {
                get { return _UserName; }
                set
                {
                    if (_UserName != value)
                    {
                        _UserName = value;
                        RaisePropertyChanged("UserName");
                    }
                }
            }
        }
    }
}
